#pragma once 
#include<iostream>
#include<string>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include<unistd.h>
#include<cstdlib>
#include<strings.h>

using namespace std;
string  defaultip="0.0.0.0";
uint16_t defaultport=8080;
const int sz=1024;
class udpserver
{
public:
udpserver(uint16_t port= defaultport,string ip=defaultip)
:ip_(ip)
,port_(port)
,isrunning_(false)
,sockfd_(0)
{}
void init()
{
sockfd_=socket(AF_INET,SOCK_DGRAM,0);
if(sockfd_<0)
  {cout<<"套接字创建失败"<<endl;
   exit(1);
  }
  cout<<"套接字创建成功"<<endl;
 
struct sockaddr_in client;
 bzero(&client,sizeof(client));

client.sin_family=AF_INET;
client.sin_port=htons(port_);
client.sin_addr.s_addr=inet_addr(ip_.c_str());
//绑定
if(bind(sockfd_,(const sockaddr*)&client,sizeof(client))<0)
   {
    cout<<"绑定失败"<<endl;
    exit(1);
   }
   cout<<"绑定成功"<<endl;

}
void run()
{
 char buffer[sz];   
while(1)
{
 struct sockaddr_in client;
 socklen_t len=sizeof(client);
 ssize_t n=recvfrom(sockfd_,buffer,sizeof(buffer)-1,0,(sockaddr*)&client,&len);

 if(n<0)
 {cout<<"服务端接收失败"<<endl;
 continue;}
 buffer[n]=0;
 string info=buffer;
 cout<<info<<endl;
 string str="[";
 str+="echo";
 str+=":]";
 str+=buffer;
sendto(sockfd_,str.c_str(),str.size(),0,(sockaddr*)&client,len);

}

}
~udpserver()
{

if(sockfd_>0) close(sockfd_);


}




private:
int sockfd_;
uint16_t port_;
string ip_;
bool isrunning_;
};